<?php

namespace app\api\controller\v2;

use app\api\controller\Common;
use think\Db;
use think\Request;

class Wish extends Common {
    /**
     * @var mixed
     */
    public $params = null;
    /**
     * @param Request $request
     */
    public function __construct(Request $request = null) {
        parent::__construct($request);
        $this->params = getRsaPostParamArr2();
    }

    /**
     * @return mixed
     */
    public function lights() {
        $data = Db::name('wish_light')
            ->where(['delete_time' => 0])
            ->order('sort desc,id asc')
            ->field('id,image,name')
            ->select();
        return $this->pass($data);
    }

    /**
     * @return mixed
     */
    public function publish() {
        $light_id = $this->params['light_id'] ?? 0;
        $content  = $this->params['content'] ?? '';
        $test     = $this->params['test'] ?? 0;

        $content=iconv("utf-8","gbk//IGNORE",$content);
        $content = mb_convert_encoding($content,'UTF-8','GBK');
        
        $contentLen = mb_strlen($content);
        if ($contentLen > 200 || $contentLen < 5) {
            return $this->miss('心愿内容长度限制5-200');
        }
        
        $cachekey = 'wish_publish'.$this->member['id'].':'.$light_id.':'.$content;
        $cache = cache($cachekey);
        if ($cache) return $this->miss('发布成功');
        cache($cachekey,1,2);

        $hasLight = Db::name('wish_light')
            ->where(['delete_time' => 0, 'id' => $light_id])
            ->find();
        if (!$hasLight) {
            return $this->miss('心愿灯选择错误');
        }

        $insert = [
            'user_id'       => $this->member['id'],
            'wish_light_id' => $light_id,
            'content'       => $content,
            'create_time'   => time(),
        ];
        if ($test) {
            $insert['state']      = 1;
            $insert['audit_time'] = $insert['create_time'];
        }
        $res = Db::name('wish')->insert($insert);
        if ($res) {
            return $this->pass('发布成功');
        }
        return $this->miss('发布失败,请稍后重试');
    }

    /**
     * @return mixed
     */
    public function delete() {
        $wish_id = $this->params['wish_id'] ?? 2;
        $wish    = Db::name('wish')->where(['id' => $wish_id, 'user_id' => $this->member['id'], 'delete_time' => 0])->find();
        if (!$wish) {
            return $this->pass('心愿已删除');
        }

        $res = Db::name('wish')->where(['id' => $wish_id])->update(['delete_time' => time()]);
        if ($res) {
            return $this->pass('已删除');
        }

        return $this->miss('删除失败,请稍后重试');
    }

    /**
     * @return mixed
     */
    public function mylists() {
        $page     = $this->params['page'] ?? 1;
        $pagesize = $this->params['pagesize'] ?? 20;
        $pagesize = $pagesize > 20 ? 20 : $pagesize;

        $where = [
            'user_id'     => $this->member['id'],
            'delete_time' => 0,
        ];

        $data = Db::name('wish')
            ->where($where)
            ->page($page)
            ->limit($pagesize)
            ->field('audit_time, delete_time', true)
            ->order('id desc')
            ->select();

        if (sizeof($data)) {
            $lights = Db::name('wish_light')->column('image', 'id');

            $bless_user_ids = Db::name('wish_bless')->where(['wish_id' => ['in', array_column($data, 'id')]])->field('user_id,wish_id')->select();
            $bless_users    = Db::name('user')->where(['id' => ['in', array_column($bless_user_ids, 'user_id')]])->column('head_portrait', 'id');

            $wish_bless_users = [];
            foreach ($bless_user_ids as $key => $value) {
                if (!isset($bless_users[$value['user_id']])) {
                    continue;
                }

                if (!isset($wish_bless_users[$value['wish_id']])) {
                    $wish_bless_users[$value['wish_id']] = [];
                }

                $wish_bless_users[$value['wish_id']][] = $bless_users[$value['user_id']];
            }

            foreach ($data as &$value) {
                $value['light_image']      = $lights[$value['wish_light_id']];
                $value['create_time']      = date('Y-m-d H:i', $value['create_time']);
                $value['bless_user_heads'] = isset($wish_bless_users[$value['id']]) ? $wish_bless_users[$value['id']] : [];
            }
        }

        return $this->pass($data);
    }

    /**
     * @return mixed
     */
    public function bless() {
        $wish_id = $this->params['wish_id'] ?? 2;
        $wish    = Db::name('wish')->where(['id' => $wish_id, 'delete_time' => 0])->find();
        if (!$wish) {
            return $this->miss('心愿飞走了~');
        }

        if ($wish['user_id'] == $this->member['id']) {
            return $this->miss('操作异常');
        }

        $hasBless = Db::name('wish_bless')->master()->where(['wish_id' => $wish_id, 'user_id' => $this->member['id']])->find();
        if ($hasBless) {
            return $this->miss('你已祝福过该心愿了');
        }

        $res = Db::name('wish_bless')->insert(['wish_id' => $wish_id, 'user_id' => $this->member['id'], 'time' => time(), 'touser_id' => $wish['user_id']]);
        if (!$res) {
            return $this->miss('祝福失败,清稍后再试');
        }

        Db::name('wish')->where(['id' => $wish_id])->setInc('bless_count');
        return $this->pass('祝福成功');
    }

    /**
     * @return mixed
     */
    public function mydata() {
        $data = Db::name('wish')->where(['user_id' => $this->member['id'], 'delete_time' => 0])->column('bless_count');

        $counts = ['wish_count' => sizeof($data), 'bless_count' => array_sum($data)];

        return $this->pass($counts);
    }

    /**
     * @return mixed
     */
    public function data() {
        $bless_count  = Db::name('wish')->where(['delete_time' => 0])->sum('bless_count');
        $wish_count   = Db::name('wish')->where(['delete_time' => 0])->count();
        $unread_count = Db::name('wish_bless')->master()->where(['touser_id' => $this->member['id'], 'is_read' => 0])->count();

        return $this->pass(compact('bless_count', 'wish_count', 'unread_count'));
    }

    /**
     * @return mixed
     */
    public function message() {
        $page     = $this->params['page'] ?? 1;
        $pagesize = $this->params['pagesize'] ?? 20;
        $pagesize = $pagesize > 20 ? 20 : $pagesize;

        $data = Db::name('wish_bless')
            ->alias('a')
            ->join('wish b', 'a.wish_id=b.id')
            ->join('wish_light c', 'b.wish_light_id=c.id')
            ->join('user u', 'a.user_id=u.id')
            ->where(['a.touser_id' => $this->member['id']])
            ->page($page)
            ->limit($pagesize)
            ->field('a.time bless_time, a.id, a.is_read,a.wish_id, b.create_time ,b.content,c.image light_image,u.name, u.head_portrait,sex,age, a.user_id,u.entertainment')
            ->order('is_read asc, id desc')
            ->select();
        $unread_ids = [];
        foreach ($data as &$value) {
            $value['bless_time']  = date('Y-m-d H:i', $value['bless_time']);
            $value['create_time'] = date('Y-m-d H:i', $value['create_time']);
            if (!$value['is_read']) {
                $unread_ids[] = $value['id'];
            }
        }

        if (sizeof($unread_ids)) {
            Db::name('wish_bless')->where(['id' => ['in', $unread_ids]])->update(['is_read' => 1]);
        }
        return $this->pass($data);
    }

    /**
     * @return mixed
     */
    public function lists() {
        $page     = $this->params['page'] ?? 1;
        $pagesize = $this->params['pagesize'] ?? 20;
        $pagesize = $pagesize > 20 ? 20 : $pagesize;
        $light_id = $this->params['light_id'] ?? 0;

        $where = [
            'w.user_id'     => ['<>', $this->member['id']],
            'w.delete_time' => 0,
            'w.state' => 1,
            'u.delete_time' => 0,
        ];

        if ($light_id) {
            $where['w.wish_light_id'] = strpos($light_id, ',') !== false ? ['in', $light_id] : $light_id;
        }

        $data = Db::name('wish')
            ->alias('w')
            ->join('user u', 'w.user_id=u.id')
            ->where($where)
            ->page($page)
            ->limit($pagesize)
        // ->fetchSql(true)
            ->field('w.id,w.user_id,w.wish_light_id,w.content,w.bless_count,w.create_time, u.name, u.head_portrait, u.sex, u.age, u.entertainment')
            ->order('audit_time desc, id desc')
            ->select();
        // var_dump($data);exit;
        if (sizeof($data)) {
            $lights         = Db::name('wish_light')->column('image', 'id');
            $bless_ids      = Db::name('wish_bless')->where(['wish_id' => ['in', array_column($data, 'id')], 'user_id' => $this->member['id']])->column('wish_id');
            $bless_user_ids = Db::name('wish_bless')->where(['wish_id' => ['in', array_column($data, 'id')]])->field('user_id,wish_id')->select();
            $bless_users    = Db::name('user')->where(['id' => ['in', array_column($bless_user_ids, 'user_id')]])->column('head_portrait', 'id');

            $wish_bless_users = [];
            foreach ($bless_user_ids as $key => $value) {
                if (!isset($bless_users[$value['user_id']])) {
                    continue;
                }

                if (!isset($wish_bless_users[$value['wish_id']])) {
                    $wish_bless_users[$value['wish_id']] = [];
                }

                if (sizeof($wish_bless_users[$value['wish_id']]) >= 6) continue;
                $wish_bless_users[$value['wish_id']][] = $bless_users[$value['user_id']];
            }
            foreach ($data as &$value) {
                $value['light_image']      = $lights[$value['wish_light_id']];
                $value['create_time']      = date('Y-m-d H:i', $value['create_time']);
                $value['is_bless']         = in_array($value['id'], $bless_ids);
                $value['bless_user_heads'] = isset($wish_bless_users[$value['id']]) ? $wish_bless_users[$value['id']] : [];
            }
        }

        return $this->pass($data);
    }

}